package com.baosight.xcyber.tm.re.domain;

import com.alibaba.fastjson.JSONObject;
import com.zeroc.IceGrid.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class  UIService extends UITreeNode {
    ServiceDescriptor serviceDescriptor;

    @Override
    public JSONObject getParam() {
        return (JSONObject) JSONObject.toJSON(serviceDescriptor);
    }

    UIService(String name, ServiceInstanceDescriptor serviceInstanceDescriptor,
              Map<String, TemplateDescriptor> serverTemplates,
              Map<String,TemplateDescriptor> serviceTemplates,Map<String, String> paramMapFromServer){
        this.type="SERVICE";
        this.serverTemplates=serverTemplates;
        this.serviceTemplates=serviceTemplates;
        String templateName = serviceInstanceDescriptor.template;
        TemplateDescriptor templateDescriptor = this.getServiceTemplates().get(templateName);

        if (templateDescriptor == null) {
            this.serviceDescriptor = serviceInstanceDescriptor.descriptor;
        } else {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.putAll(templateDescriptor.parameterDefaults);
            paramMap.putAll(serviceInstanceDescriptor.parameterValues);
            if(paramMapFromServer!=null){
                Map<String, String> paramMapTemplate=new HashMap<>();
                for(Map.Entry<String,String> entry:
                        serviceInstanceDescriptor.parameterValues.entrySet()){
                    paramMapTemplate.put(entry.getKey(),analyzeStr(entry.getValue(),paramMapFromServer));
                }
                paramMap.putAll(paramMapTemplate);
            }
            ServiceDescriptor descriptor = (ServiceDescriptor) templateDescriptor.descriptor.clone();
            replaceObject(descriptor, paramMap);
            this.serviceDescriptor = descriptor;
        }
        if ("".equals(name)) {
            this.name = this.serviceDescriptor.name;
        } else {
            this.name = name;
        }
        param= (JSONObject) JSONObject.toJSON(serviceDescriptor);
        List<AdapterDescriptor> adapters = this.serviceDescriptor.adapters;
        this.setChildren(adapters.stream().map(UIAdapter::new).collect(Collectors.toList()));
    }
}
